<?php

namespace App\Supports\Auth\Alipay;

use Carbon\Carbon;

class AlipayAuthToken extends AlipayAuthBase
{
	private $payload = [];

	private function makeRequestPayload(string $code)
	{
		$route = cs()->alipay_route;
		$config = config("alipay.{$route}");

		$this->payload = [
			'app_id' => $config['app_id'],
			'method' => 'alipay.system.oauth.token',
			'charset' => 'utf-8',
			'sign_type' => 'RSA2',
			'timestamp' => Carbon::now()->toDateTimeString(),
			'version' => '1.0',
			'grant_type' => 'authorization_code',
			'code' => $code,
			'sign' => '',
		];

		if ($config['app_cert_public_key'] && $config['alipay_root_cert']) {
			$this->payload['app_cert_sn'] = $this->getCertSN($config['app_cert_public_key']);
			$this->payload['alipay_root_cert_sn'] = $this->getRootCertSN($config['alipay_root_cert']);
		}

		$this->payload['sign'] = $this->generateSign($this->payload);
	}

	protected function getAccessTokenFromCode(string $code)
	{
		$response = null;

		try {

			$this->makeRequestPayload($code);

			$http = $this->getGuzzleClient();
			$response = $http->post($this->authUri, ['query' => $this->payload])->getBody()->getContents();
			$response = json_decode($response, true);

		} catch (Exception $e) {
			abort($e->getCode(), '参数错误，无法获取用户信息');
		}

		return $response['alipay_system_oauth_token_response']['access_token'];
	}
}
